package com.moliku.insurance.process.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.moliku.insurance.common.constant.WuTongFunction;
import com.moliku.insurance.common.response.R;
import com.moliku.insurance.common.util.MD5Utils;
import com.moliku.insurance.model.dto.wuTong.*;
import com.moliku.insurance.model.entity.wuTong.*;
import com.moliku.insurance.process.mapper.BaseOrderMapper;
import com.moliku.insurance.process.service.InsuranceCarDetailService;
import com.moliku.insurance.process.service.InsuranceCarService;
import com.moliku.insurance.process.service.WuTongService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 梧桐车险
 * @Author: yws
 * @Date: 2021/3/18 17:11
 */
@Slf4j
@AllArgsConstructor
@Service("WuTongService")
public class WuTongServiceImpl implements WuTongService {


    /**
     * 请求地址
     */
//    private final static String BASE_URL = "http://119.253.81.113/tk-link-carModel/rest";
    //代理地址
    private final static String BASE_URL = "http://8.131.255.39/wt";

    /**
     * 保单列表请求地址
     */
    private final static String POLICY_LIST_URL = "http://wechat.test.car.tk.cn/epolicy/open/channel/policyList";

    /**
     * 保单详情请求地址
     */
    private final static String DETAIL_URL = "http://wechat.test.car.tk.cn/epolicy/open/channel/detailData";

    /**
     * 成功状态码
     */
    private final static String SUCCESS_CODE = "200";

    /**
     * token
     */
    private final static String TOKEN = "1234567890ABCDEF";


    private final RestTemplate restTemplate;

    @Autowired
    private BaseOrderMapper baseOrderMapper;
    @Autowired
    private InsuranceCarService carService;
    @Autowired
    private InsuranceCarDetailService carDetailService;

    /**
     * @Description: 车型查询接口
     * @Author: yws
     * @Date: 2021/3/19 10:36
     */
    @Override
    @Transactional
    public R<Object> carModelQuery(WuTongCarQueryDTO wuTongCarQueryDTO) {
        log.info("车型查询接口{}", wuTongCarQueryDTO.toString());
        try {
            //获取token
            Map<String, Object> map = getToken(wuTongCarQueryDTO.getOrder().getChannelId());
            if (!"0".equals(map.get("code"))) {
                return R.fail("token获取失败", 4005);
            }
            String token = map.get("token").toString();
            //封装请求参数
            WuTongCarInfo carInfo = new WuTongCarInfo();
            carInfo.setVehicleBrand(wuTongCarQueryDTO.getCarInfo().getVehicleBrand());
            carInfo.setLicenseNo(wuTongCarQueryDTO.getCarInfo().getLicenseNo());
            carInfo.setEngineNo(wuTongCarQueryDTO.getCarInfo().getEngineNo());
            carInfo.setFrameNo(wuTongCarQueryDTO.getCarInfo().getFrameNo());
            carInfo.setEnrollDate(wuTongCarQueryDTO.getCarInfo().getEnrollDate());
            carInfo.setNewVehicle(wuTongCarQueryDTO.getCarInfo().getNewVehicle());
            carInfo.setEcdemicVehicle(wuTongCarQueryDTO.getCarInfo().getEcdemicVehicle());
            carInfo.setVehicleModel(wuTongCarQueryDTO.getCarInfo().getVehicleModel());
            carInfo.setChgOwnerFlag(wuTongCarQueryDTO.getCarInfo().getChgOwnerFlag());
            carInfo.setInsuredCode(wuTongCarQueryDTO.getCarInfo().getInsuredCode());
            carInfo.setOperateFlag(wuTongCarQueryDTO.getCarInfo().getOperateFlag());
            carInfo.setEffectStartTime(wuTongCarQueryDTO.getCarInfo().getEffectStartTime());
            carInfo.setVehicleCode(wuTongCarQueryDTO.getCarInfo().getVehicleCode());
            carInfo.setVehicleHyCode(wuTongCarQueryDTO.getCarInfo().getVehicleHyCode());
            carInfo.setSeatCount(wuTongCarQueryDTO.getCarInfo().getSeatCount());
            carInfo.setReplacementValue(wuTongCarQueryDTO.getCarInfo().getReplacementValue());

            //实体转json
            JSONObject object = new JSONObject();
            object.put("carInfo", JSON.toJSON(carInfo));
            //参数加签
            String strSign = getSign(TOKEN, object.toString());
            //请求head
            WuTongHead head = getHead(token, wuTongCarQueryDTO.getOrder().getProposalFormId(), WuTongFunction.CAR_MODEL_QUERY.getTag(), wuTongCarQueryDTO.getOrder().getChannelId(), strSign);
            //完整请求json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("head", JSON.toJSON(head));
            jsonObject.put("apply_content", object);
            log.info("请求体：{}", jsonObject.toString());
            //统一请求
            R<Object> objectR = sendUniformRequest(BASE_URL, jsonObject.toString());
            //成功处理数据入库
            if (200 == objectR.getCode()) {
                //根据保单号查询有没有此数据
                InsuranceCar insuranceCar = carService.selectCarByProposalFormId(wuTongCarQueryDTO.getOrder().getProposalFormId());
                if (null == insuranceCar) {
                    InsuranceCar car = new InsuranceCar();
                    car.setProposalFormId(wuTongCarQueryDTO.getOrder().getProposalFormId());
                    car.setLicenseNo(wuTongCarQueryDTO.getCarInfo().getLicenseNo());
                    car.setVinNo(wuTongCarQueryDTO.getCarInfo().getFrameNo());
                    carService.save(car);
                    //查询保单详情表
                    InsuranceCarDetail insuranceCarDetail = carDetailService.selectCarDetailByProposalFormId(wuTongCarQueryDTO.getOrder().getProposalFormId());
                    if (null == insuranceCarDetail) {
                        InsuranceCarDetail carDetail = new InsuranceCarDetail();
//                        carDetail.setCarInsId(car.getId());
                        carDetail.setProposalFormId(wuTongCarQueryDTO.getOrder().getProposalFormId());
                        //判断查车类型
                        if ("1".equals(wuTongCarQueryDTO.getCarInfo().getOperateFlag())) {
                            carDetail.setCarQueryOne(JSONUtil.toJsonStr(wuTongCarQueryDTO));
                        } else if ("2".equals(wuTongCarQueryDTO.getCarInfo().getOperateFlag())) {
                            carDetail.setCarQueryTwo(JSONUtil.toJsonStr(wuTongCarQueryDTO));
                        } else {
                            carDetail.setCarQueryFour(JSONUtil.toJsonStr(wuTongCarQueryDTO));
                        }
                        carDetailService.save(carDetail);
                    } else {
                        InsuranceCarDetail carDetail = new InsuranceCarDetail();
                        carDetail.setId(insuranceCarDetail.getId());
                        //判断查车类型
                        if ("1".equals(wuTongCarQueryDTO.getCarInfo().getOperateFlag())) {
                            carDetail.setCarQueryOne(JSONUtil.toJsonStr(wuTongCarQueryDTO));
                        } else if ("2".equals(wuTongCarQueryDTO.getCarInfo().getOperateFlag())) {
                            carDetail.setCarQueryTwo(JSONUtil.toJsonStr(wuTongCarQueryDTO));
                        } else {
                            carDetail.setCarQueryFour(JSONUtil.toJsonStr(wuTongCarQueryDTO));
                        }
                        carDetailService.updateById(carDetail);
                    }
                } else {
                    InsuranceCar car = new InsuranceCar();
                    car.setId(insuranceCar.getId());
                    car.setLicenseNo(wuTongCarQueryDTO.getCarInfo().getLicenseNo());
                    car.setVinNo(wuTongCarQueryDTO.getCarInfo().getFrameNo());
                    carService.updateById(car);
                    InsuranceCarDetail insuranceCarDetail = carDetailService.selectCarDetailByProposalFormId(wuTongCarQueryDTO.getOrder().getProposalFormId());
                    InsuranceCarDetail carDetail = new InsuranceCarDetail();
                    carDetail.setId(insuranceCarDetail.getId());
                    //判断查车类型
                    if ("1".equals(wuTongCarQueryDTO.getCarInfo().getOperateFlag())) {
                        carDetail.setCarQueryOne(JSONUtil.toJsonStr(wuTongCarQueryDTO));
                    } else if ("2".equals(wuTongCarQueryDTO.getCarInfo().getOperateFlag())) {
                        carDetail.setCarQueryTwo(JSONUtil.toJsonStr(wuTongCarQueryDTO));
                    } else {
                        carDetail.setCarQueryFour(JSONUtil.toJsonStr(wuTongCarQueryDTO));
                    }
                    carDetailService.updateById(carDetail);
                }
            }
            return objectR;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return R.fail();
    }

    /**
     * @Description: 险种初始化接口
     * @Author: yws
     * @Date: 2021/3/19 15:43
     */
    @Override
    @Transactional
    public R<Object> kindsInit(WuTongKindInitDTO wuTongKindInitDTO) {
        try {
            //获取token
            Map<String, Object> map = getToken(wuTongKindInitDTO.getOrder().getChannelId());
            if (!"0".equals(map.get("code"))) {
                return R.fail("token获取失败", 4005);
            }
            String token = map.get("token").toString();
            //封装请求参数
            WuTongCars cars = new WuTongCars();
            cars.setCarModelKey(wuTongKindInitDTO.getCars().getCarModelKey());
            cars.setChgOwnerFlag(wuTongKindInitDTO.getCars().getChgOwnerFlag());
            cars.setCarOwner(wuTongKindInitDTO.getCars().getCarOwner());
            cars.setCarOwnerIdentifyType(wuTongKindInitDTO.getCars().getCarOwnerIdentifyType());
            cars.setCarOwnerIdentifyNumber(wuTongKindInitDTO.getCars().getCarOwnerIdentifyNumber());
            cars.setTransferDate(wuTongKindInitDTO.getCars().getTransferDate());
            cars.setCertificateDateBJ(wuTongKindInitDTO.getCars().getCertificateDateBJ());
            cars.setCertificateType(wuTongKindInitDTO.getCars().getCertificateType());
            cars.setCertificateNo(wuTongKindInitDTO.getCars().getCertificateNo());
            cars.setIsNewEnergy(wuTongKindInitDTO.getCars().getIsNewEnergy());
            //实体转json
            JSONObject object = new JSONObject();
            object.put("cars", JSON.toJSON(cars));
            if (wuTongKindInitDTO.getCheckList() != null && wuTongKindInitDTO.getCheckList().size() > 0) {
                //投保查询校验信息
                List<Object> checkList = new ArrayList<>();
                for (WuTongCheckDTO checkDTO : wuTongKindInitDTO.getCheckList()) {
                    WuTongCheck wuTongCheck = new WuTongCheck();
                    wuTongCheck.setCheckCode(checkDTO.getCheckCode());
                    wuTongCheck.setCheckFlag(checkDTO.getCheckFlag());
                    wuTongCheck.setQuerySequenceNo(checkDTO.getQuerySequenceNo());
                    JSONObject check = (JSONObject) JSON.toJSON(wuTongCheck);
                    JSONObject checkObject = new JSONObject();
                    checkObject.put("check", check);
                    checkList.add(checkObject);
                }
                JSONArray array = JSONArray.parseArray(JSON.toJSONString(checkList));
                object.put("checks", array);
            }
            //参数加签
            String strSign = getSign(TOKEN, object.toString());
            //请求head
            WuTongHead head = getHead(token, wuTongKindInitDTO.getOrder().getProposalFormId(), WuTongFunction.KIND_INIT.getTag(), wuTongKindInitDTO.getOrder().getChannelId(), strSign);
            //完整请求json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("head", JSON.toJSON(head));
            jsonObject.put("apply_content", object);
            log.info("请求体{}", jsonObject.toString());
            //统一请求
            R<Object> objectR = sendUniformRequest(BASE_URL, jsonObject.toString());
            //成功处理数据入库
            if (200 == objectR.getCode()) {
                InsuranceCarDetail insuranceCarDetail = carDetailService.selectCarDetailByProposalFormId(wuTongKindInitDTO.getOrder().getProposalFormId());
                if (null != insuranceCarDetail) {
                    InsuranceCarDetail carDetail = new InsuranceCarDetail();
                    carDetail.setId(insuranceCarDetail.getId());
                    carDetail.setKindsInitData(JSONUtil.toJsonStr(wuTongKindInitDTO));
                    carDetailService.updateById(carDetail);
                }
            }
            return objectR;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return R.fail();
    }


    /**
     * @Description: 询价接口
     * @Author: yws
     * @Date: 2021/3/19 17:31
     */
    @Override
    @Transactional
    public R<Object> priceQuote(WuTongPriceQuoteDTO wuTongPriceQuoteDTO) {
        try {
            //获取token
            Map<String, Object> map = getToken(wuTongPriceQuoteDTO.getOrder().getChannelId());
            if (!"0".equals(map.get("code"))) {
                return R.fail("token获取失败", 4005);
            }
            String token = map.get("token").toString();
            //车辆信息
            WuTongCars wuTongCars = new WuTongCars();
            wuTongCars.setCarModelKey(wuTongPriceQuoteDTO.getCars().getCarModelKey());
            wuTongCars.setChgOwnerFlag(wuTongPriceQuoteDTO.getCars().getChgOwnerFlag());
            wuTongCars.setTransferDate(wuTongPriceQuoteDTO.getCars().getTransferDate());
            wuTongCars.setCertificateDateBJ(wuTongPriceQuoteDTO.getCars().getCertificateDateBJ());
            wuTongCars.setCertificateType(wuTongPriceQuoteDTO.getCars().getCertificateType());
            wuTongCars.setCertificateNo(wuTongPriceQuoteDTO.getCars().getCertificateNo());
            //实体转json
            JSONObject object = new JSONObject();

            object.put("car", JSON.toJSON(wuTongCars));
            if (wuTongPriceQuoteDTO.getPrivyList() != null && wuTongPriceQuoteDTO.getPrivyList().size() > 0) {
                //干系人(车主)信息
                List<Object> list = new ArrayList<>();
                for (WuTongPrivyDTO privyDTO : wuTongPriceQuoteDTO.getPrivyList()) {
                    WuTongPrivy wuTongPrivy = new WuTongPrivy();
                    wuTongPrivy.setInsuredFlag(privyDTO.getInsuredFlag());
                    wuTongPrivy.setInsuredName(privyDTO.getInsuredName());
                    wuTongPrivy.setIdentifyType(privyDTO.getIdentifyType());
                    wuTongPrivy.setIdentifyNumber(privyDTO.getIdentifyNumber());
                    wuTongPrivy.setMobile(privyDTO.getMobile());
                    JSONObject privyObj = (JSONObject) JSON.toJSON(wuTongPrivy);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("privy", privyObj);
                    list.add(jsonObject);
                }
                JSONArray privyArray = JSONArray.parseArray(JSON.toJSONString(list));
                object.put("privyList", privyArray);
            }
            if (wuTongPriceQuoteDTO.getRiskList() != null && wuTongPriceQuoteDTO.getRiskList().size() > 0) {
                //险种信息
                List<Object> riskList = new ArrayList<>();
                for (WuTongRiskDTO riskDTO : wuTongPriceQuoteDTO.getRiskList()) {
                    WuTongRisk wuTongRisk = new WuTongRisk();
                    wuTongRisk.setRiskCode(riskDTO.getRiskCode());
                    wuTongRisk.setEffectStartTime(riskDTO.getEffectStartTime());
                    wuTongRisk.setEffectEndTime(riskDTO.getEffectEndTime());
                    if (riskDTO.getKindList() != null && riskDTO.getKindList().size() > 0) {
                        List<Object> wuTongKindList = new ArrayList<>();
                        for (WuTongKindDTO wuTongKindDTO : riskDTO.getKindList()) {
                            WuTongKind wuTongKind = new WuTongKind();
                            wuTongKind.setKindCode(wuTongKindDTO.getKindCode());
                            wuTongKind.setAmount(wuTongKindDTO.getAmount());
                            wuTongKind.setQuantity(wuTongKindDTO.getQuantity());
                            wuTongKind.setUnitAmount(wuTongKindDTO.getUnitAmount());
                            wuTongKind.setKindFlag(wuTongKindDTO.getKindFlag());
                            JSONObject kindObj = (JSONObject) JSON.toJSON(wuTongKind);
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("kind", kindObj);
                            wuTongKindList.add(jsonObject);
                        }
                        JSONArray kindArray = JSONArray.parseArray(JSON.toJSONString(wuTongKindList));
                        wuTongRisk.setKindList(kindArray);
                    }
                    JSONObject riskObj = (JSONObject) JSON.toJSON(wuTongRisk);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("risk", riskObj);
                    riskList.add(jsonObject);
                }

                JSONArray riskArray = JSONArray.parseArray(JSON.toJSONString(riskList));
                object.put("riskList", riskArray);
            }

            //参数加签
            String strSign = getSign(TOKEN, object.toString());
            //请求head
            WuTongHead head = getHead(token, wuTongPriceQuoteDTO.getOrder().getProposalFormId(), WuTongFunction.PRICE_QUOTE.getTag(), wuTongPriceQuoteDTO.getOrder().getChannelId(), strSign);
            //完整请求json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("head", JSON.toJSON(head));
            jsonObject.put("apply_content", object);
            log.info("请求体{}", jsonObject.toString());
            //统一请求
            R<Object> objectR = sendUniformRequest(BASE_URL, jsonObject.toString());
            //成功处理数据入库
            if (200 == objectR.getCode()) {
                JSONObject data = (JSONObject) objectR.getData();
                JSONArray array = data.getJSONArray("riskList");
                //根据投保单号查询已经存库的数据
                InsuranceCar insuranceCar = carService.selectCarByProposalFormId(wuTongPriceQuoteDTO.getOrder().getProposalFormId());
                for (int i = 0; i < array.size(); i++) {
                    if (i == 0) {
                        InsuranceCar car = new InsuranceCar();
                        car.setId(insuranceCar.getId());
                        car.setRiskName(array.getJSONObject(i).getJSONObject("risk").get("riskCode").toString());
                        car.setStartDate(array.getJSONObject(i).getJSONObject("risk").get("effectStartTime").toString());
                        car.setEndDate(array.getJSONObject(i).getJSONObject("risk").get("effectEndTime").toString());
                        car.setPremium(new BigDecimal(array.getJSONObject(i).getJSONObject("risk").get("riskSumPremium").toString()));
                        carService.updateById(car);
                    }
                    InsuranceCar car = new InsuranceCar();
                    car.setProposalFormId(insuranceCar.getProposalFormId());
                    car.setLicenseNo(insuranceCar.getLicenseNo());
                    car.setVinNo(insuranceCar.getVinNo());
                    car.setRiskName(array.getJSONObject(i).getJSONObject("risk").get("riskCode").toString());
                    car.setStartDate(array.getJSONObject(i).getJSONObject("risk").get("effectStartTime").toString());
                    car.setEndDate(array.getJSONObject(i).getJSONObject("risk").get("effectEndTime").toString());
                    car.setPremium(new BigDecimal(array.getJSONObject(i).getJSONObject("risk").get("riskSumPremium").toString()));
                    carService.save(car);
                }
                InsuranceCarDetail insuranceCarDetail = carDetailService.selectCarDetailByProposalFormId(wuTongPriceQuoteDTO.getOrder().getProposalFormId());
                if (null != insuranceCarDetail) {
                    InsuranceCarDetail carDetail = new InsuranceCarDetail();
                    carDetail.setId(insuranceCarDetail.getId());
                    carDetail.setPriceQuoteData(JSONUtil.toJsonStr(wuTongPriceQuoteDTO));
                    carDetailService.updateById(carDetail);
                }
            }
            return objectR;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.fail();
    }

    /**
     * @Description: 下单及核保接口
     * @Author: yws
     * @Date: 2021/3/19 17:31
     */
    @Override
    @Transactional
    public R<Object> quoteToProposal(WuTongQuoteDTO wuTongQuoteDTO) {
        try {
            //获取token
            Map<String, Object> map = getToken(wuTongQuoteDTO.getOrder().getChannelId());
            if (!"0".equals(map.get("code"))) {
                return R.fail("token获取失败", 4005);
            }
            String token = map.get("token").toString();
            //配送人信息
            WuTongCourierInfo courierInfo = new WuTongCourierInfo();
            courierInfo.setPhoneNumber(wuTongQuoteDTO.getCourierInfo().getPhoneNumber());
            courierInfo.setAdress(wuTongQuoteDTO.getCourierInfo().getAdress());
            courierInfo.setContacts(wuTongQuoteDTO.getCourierInfo().getContacts());
            courierInfo.setProvince(wuTongQuoteDTO.getCourierInfo().getProvince());
            courierInfo.setCity(wuTongQuoteDTO.getCourierInfo().getCity());
            //实体转json
            JSONObject object = new JSONObject();

            object.put("courierInfo", JSON.toJSON(courierInfo));
            object.put("quotationNoBI", wuTongQuoteDTO.getOrder().getQuotationNoBi());
            object.put("quotationNoCI", wuTongQuoteDTO.getOrder().getQuotationNoCi());
            if (wuTongQuoteDTO.getPrivyList() != null && wuTongQuoteDTO.getPrivyList().size() > 0) {
                //干系人(车主)信息
                List<Object> list = new ArrayList<>();
                for (WuTongPrivyDTO privyDTO : wuTongQuoteDTO.getPrivyList()) {
                    WuTongPrivy wuTongPrivy = new WuTongPrivy();
                    wuTongPrivy.setInsuredFlag(privyDTO.getInsuredFlag());
                    wuTongPrivy.setInsuredName(privyDTO.getInsuredName());
                    wuTongPrivy.setIdentifyType(privyDTO.getIdentifyType());
                    wuTongPrivy.setIdentifyNumber(privyDTO.getIdentifyNumber());
                    wuTongPrivy.setMobile(privyDTO.getMobile());
                    wuTongPrivy.setCarinsureDrelation(privyDTO.getCarinsureDrelation());
                    wuTongPrivy.setEmail(privyDTO.getEmail());
                    wuTongPrivy.setNation(privyDTO.getNation());
                    wuTongPrivy.setIssuer(privyDTO.getIssuer());
                    wuTongPrivy.setCertiStartDate(privyDTO.getCertiStartDate());
                    wuTongPrivy.setCertiEndDate(privyDTO.getCertiEndDate());
                    wuTongPrivy.setSex(privyDTO.getSex());
                    wuTongPrivy.setBirthDate(privyDTO.getBirthDate());
                    wuTongPrivy.setPossesSortType("1");
                    JSONObject privyObj = (JSONObject) JSON.toJSON(wuTongPrivy);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("privy", privyObj);
                    list.add(jsonObject);
                }
                JSONArray array = JSONArray.parseArray(JSON.toJSONString(list));
                object.put("privyList", array);
            }

            //参数加签
            String strSign = getSign(TOKEN, object.toString());
            //请求head
            WuTongHead head = getHead(token, wuTongQuoteDTO.getOrder().getProposalFormId(), WuTongFunction.QUOTE_TO_PROPOSAL.getTag(), wuTongQuoteDTO.getOrder().getChannelId(), strSign);
            //完整请求json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("head", JSON.toJSON(head));
            jsonObject.put("apply_content", object);
            log.info("请求体{}", jsonObject.toString());
            R<Object> objectR = sendUniformRequest(BASE_URL, jsonObject.toString());
            if (200 == objectR.getCode()) {
                JSONObject data = (JSONObject) objectR.getData();
                InsuranceCar insuranceCar = carService.selectCarByProposalFormId(wuTongQuoteDTO.getOrder().getProposalFormId());
                InsuranceCar car = new InsuranceCar();
                car.setProposalNo(data.get("proposalNo").toString());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
                car.setInputeDate(sdf.format(new Date()));
                car.setProposalFormId(insuranceCar.getProposalFormId());
                carService.updateCarByProposalFormId(car);
                InsuranceCarDetail insuranceCarDetail = carDetailService.selectCarDetailByProposalFormId(wuTongQuoteDTO.getOrder().getProposalFormId());
                if (null != insuranceCarDetail) {
                    InsuranceCarDetail carDetail = new InsuranceCarDetail();
                    carDetail.setId(insuranceCarDetail.getId());
                    carDetail.setQuoteProposalData(JSONUtil.toJsonStr(wuTongQuoteDTO));
                    carDetailService.updateById(carDetail);
                }
            }
            return objectR;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return R.fail();
    }


    /**
     * @Description: 获取电子保单下载链接
     * @Author: yws
     * @Date: 2021/3/19 14:40
     */
    @Override
    @Transactional
    public R<Object> queryPolicyLink(WuTongOrderDTO wuTongOrderDTO) {
        try {
            //获取token
            Map<String, Object> map = getToken(wuTongOrderDTO.getChannelId());
            if (!"0".equals(map.get("code"))) {
                return R.fail("token获取失败", 4005);
            }
            String token = map.get("token").toString();
            JSONObject object = new JSONObject();
            object.put("policyNo", wuTongOrderDTO.getPolicyNo());
            //参数加签
            String strSign = getSign(TOKEN, object.toJSONString());
            //请求head
            WuTongHead head = getHead(token, wuTongOrderDTO.getProposalFormId(), WuTongFunction.QUERY_POLICY_LINK.getTag(), wuTongOrderDTO.getChannelId(), strSign);
            //完整请求json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("head", JSON.toJSON(head));
            jsonObject.put("apply_content", object);
            log.info("请求体{}", jsonObject.toString());
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
            HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), httpHeaders);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(BASE_URL, request, String.class);
            log.info("请求返回{}", responseEntity.getBody());
            JSONObject resObject = JSON.parseObject(responseEntity.getBody());
//            String reponseCode = resObject.getJSONObject("apply_content").get("reponseCode").toString();
            String messageBody = resObject.getJSONObject("apply_content").get("messageBody").toString();
            //现在调通了但是没有返回连接
            if ("成功".equals(messageBody)) {
                Map<String, String> stringMap = new HashMap<>(2);
                stringMap.put("policyLinkCIP", resObject.getJSONObject("apply_content").get("policyLinkCIP").toString());
                stringMap.put("policyLinkBZ", resObject.getJSONObject("apply_content").get("policyLinkBZ").toString());
                InsuranceCarDetail insuranceCarDetail = carDetailService.selectCarDetailByProposalFormId(wuTongOrderDTO.getProposalFormId());
                if (null != insuranceCarDetail) {
                    InsuranceCarDetail carDetail = new InsuranceCarDetail();
                    carDetail.setId(insuranceCarDetail.getId());
                    carDetail.setPolicyLinkData(JSONUtil.toJsonStr(stringMap));
                    carDetailService.updateById(carDetail);
                }
                return R.success().setData(stringMap);
            } else {
                return R.fail(messageBody, 4006);
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return R.fail();
    }

    /**
     * @Description: 确认出单
     * @Author: yws
     * @Date: 2021/3/19 14:36
     */
    @Override
    public R<Object> policyNotice(TkPolicyNoticeDTO tkPolicyNoticeDTO) {
        log.info("确定出单参数：{}", tkPolicyNoticeDTO.toString());
        /**
         *  try {
         *             //获取token
         *             Map<String, Object> map = getToken(wuTongOrderDTO.getChannelId());
         *             if (!"0".equals(map.get("code"))) {
         *                 return R.fail("token获取失败", 4005);
         *             }
         *             String token = map.get("token").toString();
         *             JSONObject object = new JSONObject();
         *             object.put("policyNo", wuTongOrderDTO.getPolicyNo());
         *             object.put("subPolicyNo_BI", wuTongOrderDTO.getSubPolicyNoBi());
         *             object.put("subPolicyNo_CI", wuTongOrderDTO.getSubPolicyNoCi());
         *             //参数加签
         *             String strSign = getSign(TOKEN, object.toJSONString());
         *             //请求head
         *             WuTongHead head = getHead(token, wuTongOrderDTO.getProposalFormId(), WuTongFunction.POLICY_NOTICE.getTag(), wuTongOrderDTO.getChannelId(), strSign);
         *             //完整请求json
         *             JSONObject jsonObject = new JSONObject();
         *             jsonObject.put("head", JSON.toJSON(head));
         *             jsonObject.put("apply_content", object);
         *             log.info("请求体{}", jsonObject.toString());
         *             HttpHeaders httpHeaders = new HttpHeaders();
         *             httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
         *             HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), httpHeaders);
         *             ResponseEntity<String> responseEntity = restTemplate.postForEntity(BASE_URL, request, String.class);
         *             log.info("请求返回{}", responseEntity.getBody());
         *             //TODO 此处返回内容还未拿到
         *         } catch (Exception e) {
         *             e.printStackTrace();
         *         }
         */
        return R.success();
    }

    /**
     * @Description: 保单列表接口
     * @Author: yws
     * @Date: 2021/3/22 14:26
     */
    @Override
    public R<Object> policyList(InsuranceCar insuranceCar) {
        try {
            List<InsuranceCar> carList = carService.selectCarByInsuranceCar(insuranceCar);
            if (null != carList && carList.size() > 0) {
                return R.success().setData(carList);
            }
            return R.fail("查询数据不存在！", 4006);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.fail();
    }

    /**
     * @Description: 保单详情接口
     * @Author: yws
     * @Date: 2021/3/22 14:26
     */
    @Override
    public R<Object> detailData(String policyNo) {
        try {
            InsuranceCarDetail insuranceCarDetail = carDetailService.selectCarDetailByPolicyNo(policyNo);
            if (null != insuranceCarDetail) {
                Map<String, Object> map = new HashMap<>(5);
                map.put("carQuery", JSON.parse(insuranceCarDetail.getCarQueryFour()));
                map.put("kindsInitData", JSON.parse(insuranceCarDetail.getKindsInitData()));
                map.put("priceQuoteData", JSON.parse(insuranceCarDetail.getPriceQuoteData()));
                map.put("quoteProposalData", JSON.parse(insuranceCarDetail.getQuoteProposalData()));
                map.put("policyLinkData", JSON.parse(insuranceCarDetail.getPolicyLinkData()));
                return R.success().setData(map);
            }
            return R.fail("此保单不存在！", 4006);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.fail();
    }

    @Override
    public R<Object> checkIssueCode(WuTongOrderDTO wuTongOrderDTO) {
        try {
            //获取token
            Map<String, Object> map = getToken("68011");
            if (!"0".equals(map.get("code"))) {
                return R.fail("token获取失败", 4005);
            }
            String token = map.get("token").toString();
            JSONObject object = new JSONObject();
            object.put("proposalNo", wuTongOrderDTO.getPolicyNo());
            object.put("businessType", "0");
            //参数加签
            String strSign = getSign(TOKEN, object.toJSONString());
            //请求head
            WuTongHead head = getHead(token, wuTongOrderDTO.getProposalFormId(), "checkIssueCode", "66773", strSign);
            //完整请求json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("head", JSON.toJSON(head));
            jsonObject.put("apply_content", object);
            log.info("请求体{}", jsonObject.toString());
            return sendUniformRequest(BASE_URL, jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.fail();
    }

    @Override
    public R<Object> getSytUrl(WuTongOrderDTO wuTongOrderDTO) {
        try {
            //获取token
            Map<String, Object> map = getToken("68011");
            if (!"0".equals(map.get("code"))) {
                return R.fail("token获取失败", 4005);
            }
            String token = map.get("token").toString();
            JSONObject object = new JSONObject();
            object.put("proposalNo", wuTongOrderDTO.getPolicyNo());
            object.put("platformId", "PC");
            object.put("paywayid", "WECHATS");
            object.put("bankNo", "");
            object.put("successNotifyUrl", "");
            object.put("failNotifyUrl", "");
            object.put("businessType", "0");
            //参数加签
            String strSign = getSign(TOKEN, object.toJSONString());
            //请求head
            WuTongHead head = getHead(token, wuTongOrderDTO.getProposalFormId(), "getSytUrl", "66773", strSign);
            //完整请求json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("head", JSON.toJSON(head));
            jsonObject.put("apply_content", object);
            log.info("请求体{}", jsonObject.toString());
            return sendUniformRequest(BASE_URL, jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.fail();
    }

    @Override
    public R<Object> resendMessage(WuTongOrderDTO wuTongOrderDTO) {
        try {
            //获取token
            Map<String, Object> map = getToken("68011");
            if (!"0".equals(map.get("code"))) {
                return R.fail("token获取失败", 4005);
            }
            String token = map.get("token").toString();
            JSONObject object = new JSONObject();
            object.put("proposalNo", wuTongOrderDTO.getPolicyNo());
            object.put("interfaceCode", "01");
            //参数加签
            String strSign = getSign(TOKEN, object.toJSONString());
            //请求head
            WuTongHead head = getHead(token, wuTongOrderDTO.getProposalFormId(), "resendMessage", "66773", strSign);
            //完整请求json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("head", JSON.toJSON(head));
            jsonObject.put("apply_content", object);
            log.info("请求体{}", jsonObject.toString());
            return sendUniformRequest(BASE_URL, jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.fail();
    }

    /**
     * @Description: 封装统一请求
     * @Author: yws
     * @Date: 2021/3/24 15:26
     */
    private R<Object> sendUniformRequest(String url, String json) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
        HttpEntity<String> request = new HttpEntity<String>(json, httpHeaders);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
        log.info("请求返回：{}", responseEntity.getBody());
        JSONObject resObject = JSON.parseObject(responseEntity.getBody());
        String reponseCode = resObject.getJSONObject("apply_content").get("reponseCode").toString();
        if (SUCCESS_CODE.equals(reponseCode)) {
            JSONObject data = resObject.getJSONObject("apply_content").getJSONObject("data");
            return R.success().setData(data);
        } else {
            String massage = resObject.getJSONObject("apply_content").get("messageBody").toString();
            return R.fail(massage, 4006);
        }
    }


    /**
     * @Description: 获取Token
     * @Param: ChannelId 渠道ID
     * @Return:
     * @Author: leoYan
     * @Date: 2021/3/19 10:09
     */
    public Map<String, Object> getToken(String channelId) {
        Map<String, Object> map = new HashMap<>();
        try {
            WuTongHead head = new WuTongHead();
            head.setVersion(WuTongFunction.VERSION.getTag());
            head.setFunction(WuTongFunction.GET_TOKEN.getTag());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            head.setTransTime(sdf.format(new Date()));
            //渠道
            head.setChannelId(channelId);
            //唯一定位一次报文请求，由发起方生成，应答方原样返回
            head.setReqMsgId(UUID.randomUUID().toString().trim().replaceAll("-", ""));
            JSONObject jsonObject = (JSONObject) JSON.toJSON(head);
            JSONObject headObject = new JSONObject();
            headObject.put("head", jsonObject);
            log.info("请求token参数：{}", headObject.toString());
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
            HttpEntity<String> request = new HttpEntity<String>(headObject.toString(), httpHeaders);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(BASE_URL, request, String.class);
            log.info("获取token返回：{}", responseEntity.getBody());
            JSONObject object = JSON.parseObject(responseEntity.getBody());
            String messageCode = object.getJSONObject("apply_content").get("messageCode").toString();
            if ("0".equals(messageCode)) {
                //0代表业务成功
                map.put("code", "0");
                String strToken = object.getJSONObject("apply_content").getJSONObject("data").get("proposalFormToken").toString();
                map.put("token", strToken);
            } else {
                map.put("code", "1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * @Description: 数据加签
     * @Param: token 固定的
     * @Param: content 请求apply_content 中的内容
     * @Return: 返回MD5加密后的签名
     * @Author: leoYan
     * @Date: 2021/3/18 18:29
     */
    private static String getSign(String token, String content) {
        return MD5Utils.MD5(token + content);
    }

    /**
     * @Description: 公共请求头
     * @Param: proposalFormToken token
     * @Param: proposalFormId 交易流水号
     * @Param: function 请求方法
     * @Param: channelId 渠道
     * @Param: sign 签名
     * @Return: WuTongHead
     * @Author: yws
     * @Date: 2021/3/19 11:46
     */
    private static WuTongHead getHead(String proposalFormToken, String proposalFormId, String function, String channelId, String sign) {
        WuTongHead head = new WuTongHead();
        head.setProposalFormToken(proposalFormToken);
        head.setVersion(WuTongFunction.VERSION.getTag());
        head.setFunction(function);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        head.setTransTime(sdf.format(new Date()));
        //唯一定位一次报文请求，由发起方生成，应答方原样返回
        head.setReqMsgId(UUID.randomUUID().toString().trim().replaceAll("-", ""));
        head.setProposalFormId(proposalFormId);
        head.setChannelId(channelId);
        head.setSignType("md5");
        head.setSign(sign);
        return head;
    }

}
